//
//  CardViewModel.swift
//  AnnCardApp
//
//  Created by Developer on 2024/06/15.
//

import Foundation
import SwiftUI

class CardViewModel: ObservableObject {
    @Published var cards: [Card] = []
    @Published var currentIndex: Int = 0
    @Published var studyProgress: [UUID: StudyProgress] = [:]
    @Published var currentSession: StudySession?
    
    var currentCard: Card? {
        guard !cards.isEmpty && currentIndex < cards.count else { return nil }
        return cards[currentIndex]
    }
    
    var totalCards: Int {
        return cards.count
    }
    
    var hasNextCard: Bool {
        return currentIndex < cards.count - 1
    }
    
    var hasPreviousCard: Bool {
        return currentIndex > 0
    }
    
    init() {
        loadCards()
        startStudySession()
    }
    
    // MARK: - 卡片导航
    
    func nextCard() {
        guard hasNextCard else { return }
        currentIndex += 1
    }
    
    func previousCard() {
        guard hasPreviousCard else { return }
        currentIndex -= 1
    }
    
    func shuffleCards() {
        cards.shuffle()
        currentIndex = 0
    }
    
    func goToCard(at index: Int) {
        guard index >= 0 && index < cards.count else { return }
        currentIndex = index
    }
    
    // MARK: - 数据管理
    
    func loadCards() {
        // 从本地存储加载卡片
        if let savedCards = loadCardsFromStorage() {
            self.cards = savedCards
        } else {
            // 如果没有保存的卡片，加载示例数据
            loadSampleCards()
        }
        
        // 加载学习进度
        loadStudyProgress()
    }
    
    func loadSampleCards() {
        cards = [
            Card(
                word: "Hello",
                translation: "你好",
                pronunciation: "/həˈloʊ/",
                definition: "Used as a greeting or to begin a phone conversation",
                example: "Hello, how are you today?",
                difficulty: .beginner,
                category: .daily
            ),
            Card(
                word: "Beautiful",
                translation: "美丽的",
                pronunciation: "/ˈbjuːtɪfəl/",
                definition: "Pleasing the senses or mind aesthetically",
                example: "She has a beautiful smile.",
                difficulty: .intermediate,
                category: .daily
            ),
            Card(
                word: "Technology",
                translation: "技术",
                pronunciation: "/tekˈnɑːlədʒi/",
                definition: "The application of scientific knowledge for practical purposes",
                example: "Modern technology has changed our lives.",
                difficulty: .advanced,
                category: .technology
            ),
            Card(
                word: "Restaurant",
                translation: "餐厅",
                pronunciation: "/ˈrestərɑːnt/",
                definition: "A place where people pay to sit and eat meals",
                example: "Let's go to that new restaurant downtown.",
                difficulty: .intermediate,
                category: .food
            ),
            Card(
                word: "Adventure",
                translation: "冒险",
                pronunciation: "/ədˈventʃər/",
                definition: "An unusual and exciting experience or activity",
                example: "Their trip to the mountains was a great adventure.",
                difficulty: .intermediate,
                category: .travel
            )
        ]
        
        // 为每个卡片初始化学习进度
        for card in cards {
            if studyProgress[card.id] == nil {
                studyProgress[card.id] = StudyProgress(cardId: card.id)
            }
        }
    }
    
    private func loadCardsFromStorage() -> [Card]? {
        guard let data = UserDefaults.standard.data(forKey: "SavedCards"),
              let cards = try? JSONDecoder().decode([Card].self, from: data) else {
            return nil
        }
        return cards
    }
    
    func saveCards() {
        if let data = try? JSONEncoder().encode(cards) {
            UserDefaults.standard.set(data, forKey: "SavedCards")
        }
    }
    
    private func loadStudyProgress() {
        guard let data = UserDefaults.standard.data(forKey: "StudyProgress"),
              let progress = try? JSONDecoder().decode([UUID: StudyProgress].self, from: data) else {
            return
        }
        studyProgress = progress
    }
    
    func saveStudyProgress() {
        if let data = try? JSONEncoder().encode(studyProgress) {
            UserDefaults.standard.set(data, forKey: "StudyProgress")
        }
    }
    
    // MARK: - 学习会话管理
    
    func startStudySession() {
        currentSession = StudySession(startTime: Date())
    }
    
    func endStudySession() {
        currentSession?.endTime = Date()
        // 保存会话数据
        saveStudySession()
        currentSession = nil
    }
    
    private func saveStudySession() {
        // TODO: 实现会话数据保存
    }
    
    // MARK: - 学习进度跟踪
    
    func markCardAsStudied(_ card: Card, isCorrect: Bool) {
        guard var progress = studyProgress[card.id] else { return }
        
        progress.reviewCount += 1
        if isCorrect {
            progress.correctCount += 1
            progress.masteryLevel = min(progress.masteryLevel + 1, 5)
        } else {
            progress.masteryLevel = max(progress.masteryLevel - 1, 0)
        }
        progress.lastReviewDate = Date()
        
        studyProgress[card.id] = progress
        
        // 更新当前会话
        currentSession?.cardsStudied.append(card.id)
        currentSession?.totalAnswers += 1
        if isCorrect {
            currentSession?.correctAnswers += 1
        }
        
        saveStudyProgress()
    }
    
    func toggleBookmark(for card: Card) {
        guard var progress = studyProgress[card.id] else { return }
        progress.isBookmarked.toggle()
        studyProgress[card.id] = progress
        saveStudyProgress()
    }
    
    // MARK: - 筛选和排序
    
    func filterCards(by difficulty: Card.Difficulty) -> [Card] {
        return cards.filter { $0.difficulty == difficulty }
    }
    
    func filterCards(by category: Card.Category) -> [Card] {
        return cards.filter { $0.category == category }
    }
    
    func getCardsNeedingReview() -> [Card] {
        return cards.filter { card in
            guard let progress = studyProgress[card.id] else { return true }
            return progress.needsReview
        }
    }
    
    func getBookmarkedCards() -> [Card] {
        return cards.filter { card in
            studyProgress[card.id]?.isBookmarked == true
        }
    }
}
